package com.cn.ZhiKeDianShang.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.cn.ZhiKeDianShang.R;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.ui.widget.CropImageView;
import com.zhihu.matisse.listener.OnSelectedListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;
import io.reactivex.functions.Consumer;

public class TestScanActivity extends AppCompatActivity implements QRCodeView.Delegate {
    private static final String TAG = TestScanActivity.class.getSimpleName();
    private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666;
    @BindView(R.id.setting_back)
    ImageView settingBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_flash)
    TextView tvFlash;

    private ZXingView mZXingView;
    //闪光灯 是否打开
    boolean isOpen;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_scan);
        ButterKnife.bind(this);
        mZXingView = findViewById(R.id.zxingview);
        mZXingView.setDelegate(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        mZXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i("Debug", "result:" + result);
//        ToastUtil.showShort(result);
        vibrate();
        mZXingView.startSpot(); // 开始识别

        Intent intent = new Intent();
        intent.putExtra("url", result);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
    }


    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e(TAG, "打开相机出错");
    }

    public void onClick(View v) {
        switch (v.getId()) {
        }
    }


    @OnClick({R.id.setting_back, R.id.tv_flash, R.id.tv_selectphoto})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.tv_flash:
                if (isOpen) {
                    mZXingView.closeFlashlight(); // 关闭闪光灯
                    isOpen=false;
                    tvFlash.setText("打开闪光灯");
                } else {
                    mZXingView.openFlashlight(); // 打开闪光灯
                    isOpen=true;
                    tvFlash.setText("关闭闪光灯");
                }
                break;
            case R.id.tv_selectphoto:
                initPermission();
                break;
        }
    }


    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(
                Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
////                    申请的权限全部允许
                    //下面是拍照操作
                    Matisse.from(TestScanActivity.this)
                            .choose(MimeType.ofImage(), false)
                            .showSingleMediaType(true)
                            .countable(true)
                            .capture(false) //true 显示拍照  false不显示拍照
                            .isCrop(false)
                            .captureStrategy(
                                    new CaptureStrategy(true, "com.cn.FeiJingDITui"))
                            .maxSelectable(1)
                            .cropStyle(CropImageView.Style.CIRCLE)
                            .isCropSaveRectangle(false)
                            .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .originalEnable(true)
                            .maxOriginalSize(10)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .setOnSelectedListener(new OnSelectedListener() {
                                @Override
                                public void onSelected(@NonNull List<Uri> uriList, @NonNull List<String> pathList) {
                                    if (uriList != null && uriList.size() > 0 && pathList != null && pathList.size() > 0) {
                                        Log.d("Leo", uriList.size() + " " + uriList.get(0) + " " + pathList.size() + " " + pathList.get(0));
                                    }
                                }
                            })
                            .forResult(1000);
                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(TestScanActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1000:
                    try {
                        //没压缩之前的文件
                        List<String> originalPath = Matisse.obtainPathResult(data);
                        Log.d("Debug", "图片的地址为" + originalPath.get(0));
                        mZXingView.decodeQRCode(originalPath.get(0));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //上传图片操作
                    break;

            }
        }


    }
}

